const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        allprices:[],
        alltotalprices:0,
        getallprice:0,//原始价格
        noavailable:"无可用",
        expirationtime:'',
        demonstrateshow:false,
        Todaysdate:0,
        alllsit:[],
        price_list:[],
      rooms_ids:0,
          alllist:{},
        totalnums:0,
      selectedIndexes:[],
        // order_min_time:'',
        order_notice:'',
        currentTab: 0,
        selectTime: false,

        room: {},
        store: {},

        times: {},
        selected: [],
        select: [],

        select_date: '',
        select_start: '',
        select_end: '',
        nums: 0,

        date_arr: [],
        date_start: '',
        date_end: '',
        date: '',
        user:{},
        canIUseGetUserProfile: false,
        id:0,
        zd_bg:'',
        unitIndex:0,
        seeDetails: true,
        zd_t:'',
        zd_price:0,
        check_mt:true,
        sf_price:0,
        deal_id:'',
        coupon_id:'',
        tg_coupon_id:'',
        coupon_type:'',
        TotalPrice:0.00,
        deposit:100,
        time: '12:01',
        spaces:'',
        arr:[
            {
          name:21,
          flag:true
        },{
          name:22,
          flag:true
        },{
          name:23,
          flag:true
        },
        {
          name:0,
          flag:true
        },{
          name:1,
          flag:true
        },{
          name:2,
          flag:true
        },
        {
          name:3,
          flag:false
        },{
          name:4,
          flag:false
        },{
          name:5,
          flag:true
        },
        {
          name:6,
          flag:true
        },{
          name:7,
          flag:true
        },{
          name:8,
          flag:true
        },  {
          name:9,
          flag:true
        },{
          name:10,
          flag:true
        },{
          name:11,
          flag:true
        },
        {
          name:12,
          flag:true
        },{
          name:13,
          flag:true
        },{
          name:14,
          flag:true
        },  {
          name:15,
          flag:true
        },{
          name:16,
          flag:true
        },{
          name:17,
          flag:true
        },
        {
          name:18,
          flag:true
        },{
          name:19,
          flag:true
        },{
          name:20,
          flag:true
        },
      ],
      totaltime:0,
      numes:'',
      nowstime:'',//现在的时间
      selecttime:'',//选择时间段
      previousData: [], // 之前选中过的项
      list:[],
      allChosedData: {},
      alltotals:0,
      coupon_money:0
    },


  goCupon:function(){
    wx.removeStorageSync('couponmoney')
    // wx.removeStorageSync('couponid')
    wx.removeStorageSync('calenlid')
    wx.removeStorageSync('allcouponid')
    wx.navigateTo({
        url: '/pages/coupon/coupon?coupons='+"youhui",
    })

},
    gotuanCupon:function(e){
    var deal_id = e.currentTarget.dataset.id;
    wx.navigateTo({
        url: '/pages/tg_coupon/tg_coupon?deal_id='+deal_id,
    })
    },
    book: function (e) {
        var id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/book/book?id=' + id
        })
    },
    alldateshadel(){
    let data=this.data.allChosedData
    // 计算总价格
    let totalCost = 0;
    for (const date in data) {
    const timeSlots = data[date];
    
    for (const timeSlot of timeSlots) {
        const [startTime, endTime] = timeSlot.time.split("-");
        const start = parseInt(startTime.split(":")[0]) * 60 + parseInt(startTime.split(":")[1]);
        const end = parseInt(endTime.split(":")[0]) * 60 + parseInt(endTime.split(":")[1]);

        const duration = (end - start) / 60; // 将分钟差值转换为小时数
        const cost = duration * parseFloat(timeSlot.price);
        totalCost += cost;
    }
    }

    console.log("总价格：", totalCost);
    let allrooms=totalCost
        this.setData({
            TotalPrice:allrooms.toFixed(2)
        })

    },
    // 获取今天的日期
    todaysdate(){
        let  today = new Date();
        let  year = today.getFullYear();
        let  month = today.getMonth() + 1; // 月份从0开始，需要加1
        let day = today.getDate();
        // 格式化月份和日期，确保为两位数
        if (month < 10) {
          month = '0' + month;
        }
        if (day < 10) {
          day = '0' + day;
        }
        let  formattedDate = year + '-' + month + '-' + day;
        this.setData({
            Todaysdate:formattedDate
        })
        let formattedTime =formattedDate; // 只获取日期部分
        let  list=this.data.allChosedData[formattedTime]
        this.data.allChosedData[formattedTime]=list.map(function(item,i){
          item.index=item.key

          return item
        })
        console.log(this.data.allChosedData[formattedTime],formattedDate,'this.data.allChosedData[formattedTime]------')
        this.setData({
         allChosedData:this.data.allChosedData
        })


    },
    unsettled: function () {

      var nums = this.data.nums;
    //   选择时间不能小于0小时
      if(!nums){
        wx.showToast({
            // this.data.order_min_time 
              title: '预定时间不能小于0小时', 
              icon: 'none'
          });
          return false;

      }
       //  续租不要时间
      if (this.data.renewals=='xuzu'&&nums<=0) {
        wx.showToast({
          // this.data.order_min_time 
            title: '预定时间不能小于0小时', 
            icon: 'none'
        });
        return false;
    }

        // this.alldateshadel()
          //  续租不要时间
        //   if(this.data.renewals=='xuzu'){
        
        //     this.data.order_min_time=0
        //     console.log(this.data.order_min_time,'this.data.order_min_time--')
        // }
        // 下面的判断
    //   if(this.data.nums< Number(this.data.order_min_time)){
    //     return    wx.showToast({
    //                 title: '选择时间不能小于'+this.data.order_min_time+'小时',
    //                 icon: 'none'
    //             });
    //           }
         
      // 执行上面的语句。
    //  只获取今天的日期
        this.todaysdate()
    
        // 上面部分
        
        if (this.data.nums=='') {
            wx.showToast({
                title: '预定时间至少'+this.data.room.start_dtime+'小时起步',
                icon: 'none'
            });
            return false;
        }
        if (this.data.TotalPrice<0||this.data.TotalPrice==0) {
            wx.showToast({
                title: '总价不能小于0元',
                icon: 'none'
            });
            return false;
        }
        //   先判断本地储存
console.log('------------2222222222',this.data.TotalPrice)
        // 判断城市是否是一致的
      let   allcouponid=wx.getStorageSync('allcouponid')
      console.log(allcouponid,'allcouponid---')
      if(allcouponid){
   //   allcouponid.city_id &&
   console.log(allcouponid.city_id,this.data.details[0].city_id,'allcouponid.city_id---')
   if(allcouponid.city_id==0){
    allcouponid.city_id=this.data.details[0].city_id
   }
   if(allcouponid.city_id!==this.data.details[0].city_id){
    let city1='该优惠券不适用于当前城市'
    let citey2='当前的优惠券适用于'+allcouponid.city_name+','+'请重新选择优惠券'
    console.log(allcouponid.city_id,this.data.details[0].city_id,'this.data.details.city_id---')
  wx.showToast({
      title:allcouponid.city_name?citey2:city1 ,
      icon: 'none'
  });
  return false;
}
console.log(allcouponid.store_name,this.data.details[0].name,'this.data.details.store_name判断店铺')
//   判断店铺
// allcouponid.store_name&&
 if(allcouponid.store_name==0){
    allcouponid.store_name=this.data.details[0].name

 }
if(allcouponid.store_name!==this.data.details[0].name){
  let shop1='该优惠券不适用于当前店铺'
  let shop2='当前的优惠券适用于'+allcouponid.store_name+'店铺,'+'请重新选择优惠券'
  wx.showToast({
      title:allcouponid.store_name?shop1:shop2 ,
      icon: 'none'
  });
  return false;
}
//  判断价格allcouponid.min&&
console.log('判断价格',allcouponid.money,this.data.money)
if(Number(allcouponid.min)>=Number(this.data.TotalPrice)){
  console.log(allcouponid.min,this.data.TotalPrice,Number(allcouponid.min),Number(this.data.TotalPrice),'4444444444')
  wx.showToast({
      // 您的优惠券金额未达到30元，无法使用
      title: '您的总价格未达到'+allcouponid.min+'元无法使用,'+'请重新选择优惠券',
      icon: 'none'
  });
  return false;
}
//  判断起始时间
const currentTimestamp = Date.now();//获取当前时间戳
this.allshaders(allcouponid.expire_time)
if(allcouponid.expire_time&&allcouponid.expire_time>=currentTimestamp){//allcouponid.expire_time<=currentTimestamp
console.log(allcouponid.expire_time,currentTimestamp,'------------获取当前时间戳')
  wx.showToast({
      // 您的优惠券金额未达到30元，无法使用
      title: `该优惠券将于 ${this.data.expirationtime} 过期，请重新选择优惠券`,
      icon: 'none'
  });
  return false;
}
      }
 
        // 下面部分
        // if (nums < this.data.room.start_dtime) {
        //     wx.showToast({
        //       // this.data.order_min_time 
        //         title: nums ? '预定时间'+this.data.room.start_dtime+'小时起' : '请选择预定时间',
        //         icon: 'none'
        //     });
        //     return false;
        // }this.data.renewals=='xuzu
      
        var room_id = this.data.id,
            date = this.data.select_date,
            timeslot = [],
            times = this.data.times,
            start = this.data.select_start,
            end = this.data.select_end;
        for (var i in times) {
            if (times[i].select) {
                timeslot.push(times[i].time);
            }
        }
        // 续租
        let Pricebreakdown=this.data.nums >= 1 && this.data.nums < 1.5 ? Number(this.data.price_list[0]) :
        this.data.nums >= 1.5 && this.data.nums <2  ? Number(this.data.price_list[1]) :
        this.data.nums >= 2 && this.data.nums < 6 ? Number(this.data.price_list[2]) :
        Number(this.data.price_list[3])
            // 判断是否小于1
            if(this.data.nums<1){
                Pricebreakdown=Number(this.data.getallprice)
            }
        console.log(Pricebreakdown,'-----------')
        // 正常下单
        app.ajax({
            url: '/api/order/addOrder',
            data: {
                room_id:room_id,//房间id
                coupon_id:wx.getStorageSync('couponid')||'',//优惠卷
                // price:this.data.room.price, //小时价
                // this.data.nums
                price:Pricebreakdown, //小时价
                // this.data.TotalPrice-Number(wx.getStorageSync('couponmoney')||0)
                total_price:this.data.TotalPrice, //总价
                pledge_price:this.data.renewals=='xuzu'?0:this.data.details[0].alldeposits, //押金
                //  pledge_price:0.01 , //押金
                start:`${this.data.select_date} ${this.data.time}`, //开始时间
                end:this.data.totaltime, //结束时间
                use_hours:this.data.nums , // 使用时长
                time_periods:this.data.allChosedData, //预订的时间段
                is_xu:this.data.renewals=='xuzu'?1:''
            },
            success: res => {
                if (res.code == 1) {
                    console.log(res,'res----------code')
                    wx.navigateTo({
                        url: '/pages/unsettled/unsettled?order_id=' + res.data.id+"&TotalPrice="+ this.data.TotalPrice+"&deposit="+  this.data.deposit
                    })
                }else if (res.code == 301) {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    });

                    //倒计时延迟2秒才行
                    wx.navigateTo({
                        url: '/pages/account_chongzhi/account_chongzhi'
                    })

                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                }
            }
        }, 1);
    },
    allshaders(){
    // 假设 expire_time 的值为 1705030910，单位为秒
    let expireTime = 1705030910 * 1000; // 将秒转换为毫秒
    let date = new Date(expireTime);
    let year = date.getFullYear(); // 获取年份
    let month = date.getMonth() + 1; // 获取月份（注意：月份从 0 开始，需要加 1）
    let day = date.getDate(); // 获取日期
    let hours = date.getHours(); // 获取小时
    let minutes = date.getMinutes(); // 获取分钟

    let formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
    this.setData({
        expirationtime:formattedDate
    })
    // console.log(formattedDate); // 输出格式化后的日期时间，如 "2024-01-10 17:28"

    },
    starelist:function(){


    },
    stopBubb: function () {
        return false
    },
    callPhone(e) {
        wx.makePhoneCall({
            phoneNumber: this.data.store.mobile,
            success: function () {},
        })
    },
    select_time: function () {
      this.orderhaderl()
      this.getSelectedTimes()
      let select_date = '2024-01-03';
      let dateObj = new Date(select_date);
      dateObj.setDate(dateObj.getDate() + 1);
    //   console.log(dateObj.toISOString().split('T')[0]);
    //   console.log(this.data.select_date,'this.data.select_date---222')
        this.setData({
            selectTime: true,
            // select_date:dateObj.toISOString().split('T')[0]
        });
    },
    close_time: function () {
    // 获取当前时间
    var currentDate = new Date()
    // 格式化为指定格式
    var year = currentDate.getFullYear(); // 获取年份
    var month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 补零操作
    var day = String(currentDate.getDate()).padStart(2, '0'); // 补零操作
    // 将格式化后的时间拼接成指定格式
    var formattedDate = year + '-' + month + '-' + day;
      this.setData({
        allChosedData:{},
        nums:0, 
        select_date:formattedDate,
        totaltime:'----',
        TotalPrice:0,
        alltotals:0,
        times:[]
      })
        this.setData({
            selectTime: false
        });
        this.getSelectedTimes()
        this.alldateshadel()
    },
    // 选择最大的日期和最小的日期选择出来
    confirmtimehaderl(){
           console.log(this.data.allChosedData,'this.data.allChosedData2')
        const dates = Object.keys(this.data.allChosedData).filter(key => this.data.allChosedData[key].length > 0);
        const sortedDates = dates.sort();
        const minDate = sortedDates[0];
        const maxDate = sortedDates[sortedDates.length - 1];
        const minDateData = (this.data.allChosedData[minDate][0]).time.split('-')[0];
        const length=(this.data.allChosedData[maxDate]).length-1
        const maxDateData = (this.data.allChosedData[maxDate])[length].time.split('-')[1]
        const combinedString = `${maxDate} ${maxDateData}`;
        this.setData({
            select_date:minDate,
            totaltime:combinedString,
            time:minDateData,
        })
        this.alldateshadel()
    },
    confirm_time: function () {
         //  续租不要时间
    // if(this.data.renewals=='xuzu'){
        
    //     this.data.order_min_time=0
    //     console.log(this.data.order_min_time,'this.data.order_min_time--')
    // }
    // 先注释一下
      if(this.data.nums< Number(this.data.room.start_dtime)){
        return    wx.showToast({
                    title: '选择时间不能小于'+this.data.room.start_dtime+'小时',
                    icon: 'none'
                });
              }
      let  data=this.data.times
    let kong=data.map(function(item,index){
      item.index=index+1
       return  item
       }) 
       data=kong
     
        
// 最下方
        // 更新时间
        this.saveChosedTimes()
       
           this.confirmtimehaderl()
            //判断价格（如果是1个小时，就按照原价）
               if(this.data.alltotals<1){
                   this.setData({
                    // 小时总价格加上押金（续租没做）
                TotalPrice: this.data.renewals=='xuzu'?this.data.alltotals*Number(this.data.getallprice):this.data.alltotals*Number(this.data.getallprice)+Number(this.data.details[0].alldeposits)
                })
                 console.log(this.data.alltotals,Number(this.data.getallprice),Number(this.data.details[0].alldeposits),'---------')
               }else  if(this.data.alltotals>=1){
                    Number(this.data.price_list[0]) 
                    this.setData({
                        // 小时总价格加上押金（续租没做）
                    TotalPrice: this.data.renewals=='xuzu'?this.data.alltotals*Number(this.data.price_list[0]):this.data.alltotals*Number(this.data.price_list[0])+Number(this.data.details[0].alldeposits)
                    })
                    console.log('503行判断价格',this.data.alltotals,Number(this.data.price_list[0]))
                    console.log('1个小时,2个小时，3个小时，4个小时')
               }
                if(this.data.alltotals>=1.5){
                Number(this.data.price_list[1]) 
                this.setData({
                    // 小时总价格加上押金（续租没做）
                    TotalPrice: this.data.renewals=='xuzu'?this.data.alltotals*Number(this.data.price_list[1]):this.data.alltotals*Number(this.data.price_list[1])+Number(this.data.details[0].alldeposits)

                })

               } 
                if(this.data.alltotals>=2){
                Number(this.data.price_list[2]) 
            
                this.data.TotalPrice= this.data.renewals=='xuzu'?this.data.alltotals*Number(this.data.price_list[2]):this.data.alltotals*Number(this.data.price_list[2])+Number(this.data.details[0].alldeposits)
                this.setData({
                    
                    // 小时总价格加上押金（续租没做）
                    TotalPrice:this.data.TotalPrice
                   
                })
                console.log(this.data.alltotals,Number(this.data.price_list[2]),this.data.details[0].alldeposits,this.data.alltotals*Number(this.data.price_list[2]),'this.data.alltotals,Number(this.data.price_list[0]),this.data.details[0].alldeposits')
               }
                if(this.data.alltotals>=6){//包夜
                Number(this.data.price_list[3]) 
                this.setData({
                  // 小时总价格加上押金（续租没做）
                  TotalPrice: this.data.renewals=='xuzu'?this.data.alltotals*Number(this.data.price_list[3]):this.data.alltotals*Number(this.data.price_list[3])+Number(this.data.details[0].alldeposits)

                })
                console.log('超过了6个小时')

               }


        //  这里写错了
    //   let TotalPrices=Number(this.data.room.price) * this.data.nums+Number(this.data.deposit)-Number(wx.getStorageSync('couponmoney')||0)
      console.log(wx.getStorageSync('couponmoney'),'点击了确定的按钮--')
        this.setData({
            selectTime: false,
            // TotalPrice:TotalPrices.toFixed(2),
            // -Number(this.data.user.money)
            // zd_t: this.data.zd_t=this.data.nums,
            // sf_price:Number(this.data.room.price) * this.data.nums+this.data.deposit,
        });
        console.log(this.data.TotalPrice,'this.data.TotalPricethis.data.TotalPrice')
    //   this.alldateshadel()
    },

    // 滑动切换tab
    bindChange: function (e) {
        var that = this;
        that.setData({
            currentTab: e.detail.current
        });
    },
    slidertimes2:function(){
        // 
        var Largetime=this.data.select_date+`ms${this.data.spaces}`+this.data.time 
        Largetime= Largetime.replace('ms','\t')
        　var date = new Date(Largetime);
        　　var timestamp = date.getTime();
            timestamp=timestamp+this.data.numes*3600000
            this.sliderchange(timestamp)
    },

    // 点击tab切换
    swichNav: function (e,is) {
        
        let list=[]
        list.push(this.data.items)
      
          console.log()
        let _this = this
        this.saveChosedTimes()
        if(e.currentTarget.dataset.date!==this.data.nowstime){
            this.setData({
                selecttime: 0,
            })
        }else if(e.currentTarget.dataset.date==this.data.nowstime){
         this.bindDatePackage()
        }
        // 下面
        var date = e.currentTarget.dataset.date;
        if (this.data.select_date == date) {
            return false;
        } else {
            this.setData({
                select_date: date
            });
            this.slidertimes2();//更新
            //接口调用
            this.getSelectedTimes()
    
        }
    },
    saveChosedTimes() {

    var notselected=[]
      var chosedTimeIndexs = [] // 选中的时间列表下标
      var key = 'allChosedData.' + this.data.select_date // 获取切换前的选中日期，并生成对应的key
      this.data.times.forEach((t, idx) => {
        if (t.select||!t.select) {//   if (t.select) {
          if(t.select){
            chosedTimeIndexs.push(t)
          }
          notselected.push(t)

        }else if(t.select||!t.select){
            // console.log(notselected,'notselected--')
        }
      })
      // 存储：记录切换前选中的数据到allChosedData
      var obj = {}
      obj[key] = chosedTimeIndexs
    //  console.log(obj[key],obj,'----this.setData(obj)')
            this.setData(obj)
    //   console.log(arrs,'----arrs')
    //   下一个储存
      var objs={}
      this.setData(objs)
      objs[key] = chosedTimeIndexs
     
        //   更新数量
        this.Updatequantity()
        
    },
    Updatequantity(){

    //   更新数量
        var allDatas=Object.values(this.data.allChosedData)
        var count = 0;
        for (let i = 0; i < allDatas.length; i++) {
        const innerArray = allDatas[i];
        for (let j = 0; j < innerArray.length; j++) {
            const item = innerArray[j];
            if (item.select === true) {
            count++;
   
            }
        }
 
        // 更新数量下一个
        // var allDatasfns=Object.values(this.data.allChosedData)
        // var count = 0;
        // for (let i = 0; i < allDatasfns.length; i++) {
        // const innerArray = allDatasfns[i];
        // for (let j = 0; j < innerArray.length; j++) {
        //     const item = innerArray[j];
        //     if (item.select === true) {
        //     count++;
   
        //     }
        // }

 }
 

 this.setData({
       nums:count*0.25,
       alltotals:count*0.25
   })
    },
    bindDatePackage(){
        var now = new Date();
        var hours = now.getHours()+':';
        var minutes = now.getMinutes();
        this.data.time= hours+minutes
            this.setData({
                selecttime: this.data.time,
                time: this.data.time
            })
    },
    bindDateChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.saveChosedTimes() // 记录切换日期前的选择
        var date = e.detail.value;
        this.setData({
            date: date,
            select_date: date
        })
        this.getSelectedTimes();
        this.slidertimes2()
    },
    // 开始
    selectTime: function (e) {
      var index = e.currentTarget.dataset.index;
      var times = this.data.times;
      if (times[index].flag === 0||times[index].flag === 2) {
        return; // 如果当前时间段不可选，则直接返回
      }
      if (times[index].select) {
            //  每个对象为true选中出来
     let arr1=times.filter(function(k,i){
          
           if(k.select==true){
               return k
           }
        })
         
         times[index].select = false; // 如果已经选中，则取消选中
    
         console.log(arr1,'arr1----')
        //   选中第一个是否为false
     // 记录第一个对象的 select 属性值
     let arr2=  arr1.filter(function(k,i){
           if(k.select == false){
               k.i=i
            return k
           }
       })
       let arr3= arr1.slice(arr2[0].i)//返回一个新数组
        arr3=arr3.map(function(k,i){
            k.select=false
          return k
        })
        console.log(arr1,arr2,arr3,'---arr2')
        // this.setData({
        //   nums:39
        // })
        this.confirm_times()
        if(this.data.nums=-0.25){
          this.setData({
            nums:0
          })
        }
      
      } else {
      
        times[index].select = true; // 如果未选中，则选中
        // 先判断今天的日期是否为true
        times= times.map(function(item,index){
            item.index=index+1
            return  item
        })
        // 先判断第一个是否为true
         let firstone=this.data.times.find(function(k,i){
             if(k.select==true){
                return k
             }
       })
       let arrs=this.data.times
       let arr3=[]
       arr3.push(arrs)
       this.setData({
        alllsit:arr3
       })
            // 拿到数组对象中符合条件的最后一个元素
            let data2 = this.data.alllsit[0].slice().reverse();
         let  flag2=data2.find(function(item,i){
            if(item.select==true){
                return item
             }
              
      })
      if(flag2){
  //   截取第一个和最后一个值
  let arr4= this.data.times.slice(firstone.index-1,flag2.index)
   arr4=arr4.map(function(k,index){
        k.select=true
        return k
    })
  //  console.log(arr4,44444)
    console.log(firstone.index,flag2,arr4,44444)
    this.confirm_times()
      }
  
   

       //判断最后一个是否为true
      // let  data2=this.data.times
    //     // 拿到数组对象中符合条件的第一个元素
    //    let  flag1=data.findIndex(function(item,index){
    //         return item.select==true
    //     })
 
    //   //  截取第一个元素和最后一个中间值
    //   console.log(data,'data------')
    //   data.slice(flag1.index,flag2.index)
    //   // 判断对象中的每个select是否=true
    // let flag3=data.every(function(item,index){
    //     return item.select==true
    //   })
    //     console.log(data,flag1,flag2,flag3,'data------')
        // 
  
        this.setData({
          nums:this.data.alltotals
        })
      }
      this.setData({
        times: times,
        nums:this.data.totalnums
      });
      this.updateSelection(); // 更新选中状态
    },
    updateSelection: function () {
    
      var times = this.data.times;
      var select_start = -1;
      var select_end = -1;
      var hasSelected = false;
      
      for (var i = 0; i < times.length; i++) {
       
        if (times[i].select) {
         
          if (!hasSelected) {
            select_start = i;
            hasSelected = true;
            console.log(11)
          }
          console.log(12)
          select_end = i;
        }
     
       this.setData({
         nums:this.data.alltotals-0.25
       })
      }
      if (select_start !== -1 && select_end !== -1) {
        this.checkInterval(select_start, select_end); // 检查选中时间段是否有间隔选择

      }

    },
    checkInterval: function (start, end) {
      var times = this.data.times;
      for (var i = start + 1; i < end; i++) {
        if (times[i].flag ===0||times[i].flag== 2) {
            times[i].select=false
            // tiems[i].select=false
            console.log()
          wx.showToast({
            title: '不可以间隔选择',
            icon: 'none'
          });
          times[i].select = false; // 取消非法选中
          // times[15].select=false
          // 使用 slice() 方法截取索引为 13 到 19 的对象
        const slicedObjects = times.slice(start, end+1);
                slicedObjects.reverse(slicedObjects)
        // 打印截取后的对象
        let foundFlag0 = false;
        slicedObjects.forEach((object) => {
          if (object.flag === 0) {
            foundFlag0 = true;
          }
          
          if (foundFlag0) {
            object.select = false;
          }
        });
          console.log( times[i],slicedObjects,start,end,' times[i] times[i]')
          this.setData({
            nums:this.data.alltotals,
         
          })
        }
      }
      this.setData({
        times: times,
      });
      this.calculateTotal(); // 计算总时长
    },
    calculateTotal: function () {
      var times = this.data.times;
      var total = 0;
      for (var i = 0; i < times.length; i++) {
        if (times[i].select) {
          total += 0.25; // 假设每个时间段长度为0.5小时
        }
      }
     
            //   更新数量
        this.saveChosedTimes()
        // 判断对象中的key有多少个
        // let keys=this.data.allChosedData
        //  let alls=Object.values(keys)
      
    },
    // 上面

    // 下面
    getTimes: function (selected) {
        var times = {},
            open = this.data.store.open,
            open_key = this.getTimeKey(open),
            close = this.data.store.close,
            close_key = this.getTimeKey(close);
        selected = selected || [];
   
        for (var i = 0; i < 48; i++) {
            var h = parseInt(i / 2),
                m = 30 * (i % 2),
                key = h * 100 + m,
                time = ('0' + h).slice(-2) + ':' + ('0' + m).slice(-2),
                disabled = false;
            if (selected.indexOf(time) > -1) disabled = true;
            if (open_key != close_key && (key < open_key || key > close_key)) disabled = true;
            times[key] = {
                key: key,
                time: time,//时间
                disabled: disabled,//true绿色。false灰色（不可选中）
                flag:0,//0使用中//1预留保洁//2可以选中
                index:i//id
            };
          
        }
        
        this.setData({
            times: times,
            nums: 0,
            select_start: '',
            select_end: '',
        })
       
    },
    getTimeKey: function (time) {
        if (!time) return 0;
        var arr = time.split(':');
        return arr[0] * 100 + arr[1] * 1;
    },
    bindTimeChange: function(e) {
   

        this.setData({
          time: e.detail.value
        })
        this.slidertimes2()
      },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      let  rooms_ids=options.id
      let renewals=options.renewals
      let price_list=wx.getStorageSync('allrooms')
      let getallprice= wx.getStorageSync('getallprice')
    //   所有价格表
     let  allprices=price_list
     let  allprices2=["60分钟","90分钟","120分钟","6小时起"];
      if(allprices.length){
        let objArr = allprices.map(function(item,index) {
                return {value: item,
                time:allprices2[index]
            };
          });
          this.setData({
            allprices:objArr
          })
        //   遍历时间
      }

    //   alltotalprices
      console.log(price_list,'price_list-----')
       this.setData({
        rooms_ids:rooms_ids,
        renewals:renewals,
        price_list:price_list,
        getallprice:getallprice,
       
       })
      //  this.delalhadel()
        var token=wx.getStorageSync('token')
        if (!token) {
            
            wx.showToast({
              title: '用户未登录',
              icon: 'none',
              duration: 2000
            });
            // setTimeout(function(){

            //     this.data.demonstrateshow=true
            // },1300)
            setTimeout(function () {
              wx.navigateTo({
                url: '/pages/login/login'
              });
            }, 0); // 延迟1秒后跳转
            return false;
          }
    // 获取当前的年，月，日
    var now = new Date();
    var year = now.getFullYear()+ '-';
    var month = now.getMonth()+1+ '-';
    var date = now.getDate();
    var hours = now.getHours()+':';
    var minutes = (now.getMinutes() < 10 ? '0' + (now.getMinutes()) : now.getMinutes()) ;
    // var minutes = now.getMinutes();
    // var seconds = now.getSeconds();
    this.data.nowstime=year + month + date  
    this.data.time= hours+minutes
    // 下面
        if (wx.getUserProfile) {
            this.setData({
                canIUseGetUserProfile: true,
                nowstime:this.data.nowstime,
                time: this.data.time,
                selecttime:this.data.time,
              
            })
        }
        var that = this
        var sence_id=decodeURIComponent(options.scene).split('=')[1]
        wx.getSystemInfo({
            success: function (res) {
                
                that.setData({
                    clientHeight: res.windowHeight - 176
                });
            }
        })
    
        var id = options.id || sence_id,
            stores = wx.getStorageSync('stores'),
            store, room,room_img=[],details=[];
            this.data.id = id
        for (var i in stores) {
          let alldeposits=wx.getStorageSync('alldeposits')
            for (var j in stores[i].rooms) {
                if (stores[i].rooms[j].id == id) {
                    room = stores[i].rooms[j];
                    store = stores[i];
                    details.push({
                      id: stores[i].id,
                      address: stores[i].address,
                      lat: stores[i].lat,
                      lon: stores[i].lon,
                      name: stores[i].name,
                    //  获取城市id
                    city_id:stores[i].city_id,
                    // 获取押金
                    alldeposits:this.data.renewals=='xuzu'?0: Number(alldeposits),
                    // 获取价格：Get all prices
                    // 获取时长
                    // start_dtime:stores[i].start_dtime
                    });
                }
            }
        }
       
        room_img.push(room.image,room.image1,room.image2)
        var box_time=[],
        box_t  = store.zd_time
        this.data.zd_t = box_t[0];
        this.data.zd_price = room.price
        this.data.sf_price = room.price*box_t[0]
        // this.data.sf_price =  Number(this.data.TotalPrice)
        for (var i in box_t) {
          box_time[i] = [{'t':box_t[i],'c':box_t[i]+'小时'}]
        }
         box_time = [].concat.apply([], box_time);
        if (!store || !room) {
            wx.showToast({
                title: '查看内容不存在',
                icon: 'none'
            });
            setTimeout(function () {
                wx.navigateBack({
                    delta: 1
                })
            }, 1500);
        }
        this.setData({
            id: id,
            room: room,
            store: store,
            room_img:room_img,
            details:details,
            box_time:box_time,
            sf_price:room.price*box_t[0],
            zd_t:this.data.zd_t
        });

        var date_arr = [];
        for (var i = 0; i < 7; i++) {
            var now = new Date().getTime() + i * 86400000;
            date_arr.push(this.getDate(now,i));
        }
        console.log(date_arr);
        var start_date = this.getDate(Date.now() + 86400000 * 3),
            end_date = this.getDate(Date.now() + 86400000 * 30);
        this.setData({
            date_arr: date_arr,
            date_start: start_date.date,
            date_end: end_date.date,
            select_date: date_arr[0].date,
            deposit:wx.getStorageSync('deposit')||0
         
        });

        this.getSelectedTimes();
        // this.minimumduration()
        if(options.indexs=="quxiao"){
            wx.removeStorageSync('couponid')
        }
   
    },
    //自定选择时间盒子
    zd_time:function(e){
      this.data.zd_t = e.target.dataset.t;
      this.data.sf_price = this.data.zd_t*this.data.zd_price;
      let index = e.target.dataset.index;
      this.setData({
        unitIndex: index,
        zd_t:this.data.zd_t,
        sf_price: this.data.sf_price
      })
    },
    see_details: function () {
      var seeDetails = this.data.seeDetails
      seeDetails = !seeDetails
      this.setData({
        seeDetails: seeDetails
      })
    },

    listenerBtnGetLocation:function(e){
        var lat = e.currentTarget.dataset.lat;
        var lon = e.currentTarget.dataset.lon;
        var name = e.currentTarget.dataset.name;
        var address = e.currentTarget.dataset.address;
       console.log(lat,lon,'lonlon跳转了')
       
        wx.getLocation({
          type: 'gcj02',
          success: function(res) {
            wx.openLocation({
              latitude:Number(lat) ,
              longitude:Number(lon) ,
              scale: 28,
              name: name,
              address: address
            });
          },
          fail: function(err) {
            console.log(err);
          },
          complete: function(info) {
            console.log(info);
          }
        });
      
    },
    getDate: function (now,i) {
        var date = new Date(now),
            y = date.getFullYear(),
            m = date.getMonth() + 1,
            w = date.getDay(),
            d = date.getDate(),
            m = ('0' + m).slice(-2);
            d = ('0' + d).slice(-2);
            weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return {
            week: weeks[w],
            date: y + '-' + m + '-' + d,
            name: m + '月' + d + '日',
            operate:false,//false未选中，true选中//未选中要放送请求
            index:i
        };
    },
    getSelectedTimes: function () {
        var _this = this
        app.ajax({
          // url: '/api/index/roomTimes',
          url:'/api/user/getTimePeriod ',
          data: {
            room_id: this.data.id,
            date: this.data.select_date,
            is_xu:this.data.renewals=='xuzu'?1:''
          },
          success: res => {
            if (res.code == 1) {
              let arr = res.data
           
              // chosedTime是选择后的日期, historyTimeIndexs是我们之前存储的选择后的时间下标
              let historyTimeIndexs = _this.data.allChosedData[_this.data.select_date] || []
              if (historyTimeIndexs.length > 0) {
                historyTimeIndexs.forEach(h => {
                  let idx = arr.findIndex(a => a.time === h.time)
                  if (idx > -1) {
                    arr[idx].select = true
                  }
                })
              } 
            //   获取所有的数据
            // let alllist = _this.data.alllist[_this.data.select_date] || []
            // if (alllist.length > 0) {
            //     alllist.forEach(h => {
            //     let idx = arr.findIndex(a => a.time === h.time)
            //     if (idx > -1) {
            //       arr[idx].select = true
            //     }
            //   })
            // } 
              this.setData({
                times: arr
              })
            }
          }
        });
    },
    userinfo: function() {
      
        app.ajax({
            url: '/api/user/userinfo',
            success: res => {
                // console.log(2222222222222)
                if (res.code == 1) {
                    wx.setStorageSync('user', res.data);
                    let ids=wx.getStorageSync('couponid')
                    let  calenlid=wx.getStorageSync('calenlid')
                    if(!ids){
                        // res.data.coupon_num=0,
                        // this.data.noavailable= res.data.coupon_num
                        this.setData({
                            noavailable:this.data.noavailable
                        })
                    }
                    
                    this.setData({
                        user: res.data
                    })
                    console.log(this.data.user.coupon_num,'this.data.user.coupon_numthis.data.user.coupon_num')
                     if(calenlid){
                            this.setData({
                                coupon_money:'当前有',
                                coupon_title:this.data.user.coupon_num+'张'
                            })
                                    }

                    //   let ids=wx.getStorageSync('couponid')
                    //         if(!ids){
                    //            this.data.user.coupon_num=0
                    //              this.setData({

                    // })
                    //         }

                }
            
                
            },
          
        })
    },
    getScanStores:function(){
            app.ajax({
                url: '/api/index/stores',
                data: {},
                success: res => {
                    if (res.code == 1) {
                        wx.setStorageSync('stores', res.data);
                        var stores = res.data
                        var id = this.data.id,
                        stores = wx.getStorageSync('stores'),
                        store, room;
                    for (var i in stores) {
                        for (var j in stores[i].rooms) {
                            if (stores[i].rooms[j].id == id) {
                                room = stores[i].rooms[j];
                                store = stores[i];
                            }
                        }
                    }
                    this.setData({
                        id: id,
                        room: room,
                        store: store
                    });


                    } else {
                        wx.removeStorageSync('stores');
                        this.setData({
                            details:[]
                        })
                    }
                }
            })
    },
    login: function(e) {
        let token=wx.getStorageSync('token')
        if (!token){
            console.log('getUserProfile')
            wx.getUserProfile({
                desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                success: (res) => {
                    console.log(res)
                    if (!res.userInfo) {
                        wx.showToast({
                            title: '未获取到用户信息',
                            icon: 'none'
                        });
                        return;
                    }
                    wx.setStorageSync('userinfo', res.userInfo);
                    wx.navigateTo({
                        url: '/pages/login/login'
                    })
                }
            })
        } else {
            if (!e.detail.userInfo) {
                wx.showToast({
                    title: '未获取到用户信息',
                    icon: 'none'
                });
                return;
            }
            wx.setStorageSync('userinfo', e.detail.userInfo);
            wx.navigateTo({
                url: '/pages/login/login'
            })
        }
    },
    sliderchange:function(e){
        var date = new Date(e); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
        var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
        var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) ;
        this.data.totaltime=Y + M + D + h + m 
        // var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
        this.setData({
            totaltime: this.data.totaltime
        })
    },
    slider3change:function(e){
        this.setData({
            numes: e.detail.value
        })
        var Largetime=this.data.select_date+`ms${this.data.spaces}`+this.data.time 
        Largetime= Largetime.replace('ms','\t')
    　　var date = new Date(Largetime);
    　　var timestamp = date.getTime();
        timestamp=timestamp+e.detail.value*3600000
        this.sliderchange(timestamp)
       
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
       
        var stores = wx.getStorageSync('stores')
        if(stores == null || stores == ''){
            this.getScanStores()
        }
        this.userinfo();
        this.orderhaderl()
        this.tokenhaderl()
     
    },
    tokenhaderl(){
        var token=wx.getStorageSync('token')
        if (!token) {
            // this.data.demonstrateshow=!this.data.demonstrateshow
            wx.showToast({
              title: '用户未登录',
              icon: 'none',
              duration: 2000
            });
            // setTimeout(function(){

            //     this.data.demonstrateshow=true
            // },1300)
            setTimeout(function () {
              wx.navigateTo({
                url: '/pages/login/login'
              });
            }, 0); // 延迟1秒后跳转
            return false;
          }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        wx.showLoading({
            title: '加载中...'
          });
          // 模拟异步请求最新数据
          setTimeout(() => {
            // 在这里执行获取最新数据的逻辑，比如调用接口获取数据
            this.getSelectedTimes()
            this.orderhaderl()
            // this.minimumduration()
            // 数据获取完成后隐藏加载提示
            wx.hideLoading();
            // 停止当前页面下拉刷新
            wx.stopPullDownRefresh();
          }, 1000);
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
 
    order_pay: function () {
        var room_id = this.data.id;
        var zd_t = this.data.zd_t;

        var post_data = {
          room_id: room_id,
          zd_t:zd_t,
          deal_id:this.data.deal_id,
          coupon_type:this.data.coupon_type,
          coupon_id:this.data.coupon_id,
          tg_coupon_id:this.data.tg_coupon_id
      }
        wx.showModal({
            title: '确认订单？',
            //content: '这是一个模态弹窗',
            success (response) {
              if (response.confirm) {
                console.log('用户点击确定')
                app.ajax({
                    url: '/api/order/addOrder',
                    data:post_data,
                    success: res => {
                        if (res.code == 1) {
                            wx.navigateTo({
                                url: '/pages/opening_code/opening_code?order_id=' + res.data.id+'&lists'+res.data
                            })
                        // 余额不足跳转到充值页面
                        } else if (res.code == 301) {
                            wx.showToast({
                                title: res.msg,
                                icon: 'none'
                            });

                            //倒计时延迟2秒才行
                            setTimeout(()=>{
                                wx.navigateTo({
                                    url: '/pages/account_chongzhi/account_chongzhi'
                                })
                            },1000)

                        }else if (res.code == 400) {
                            wx.showToast({
                                title: res.msg,
                                icon: 'none'
                            });
                            //倒计时延迟2秒才行
                            setTimeout(()=>{
                                wx.navigateTo({
                                    delta: 1
                                })
                            },3000)
                        } else if (res.data.code == -2) {
                            wx.showToast({
                                title: '未登录或登陆已失效',
                                icon: 'none'
                            });
                            wx.navigateTo({
                                url: '/pages/login/login'
                            })
                            return false;
                        }
                        else {
                            wx.showToast({
                                title: res.msg,
                                icon: 'none'
                            });
                        }
                    }
                }, 1);

              } else if (response.cancel) {
                console.log('用户点击取消')
              }
            }
          })

    },
    orderhaderl(){
 app.ajax({
            url: '/api/order/orderNotice',
            success: res => {
                if (res.code == 1) {
                  this.setData({
                    order_notice:res.data.order_notice
                  })
                }
            }
        }, 1);
          

    },
    minimumduration(){
        app.ajax({
            url: '/api/order/orderMinTime',
            data:{
                code:this.data.exchangeCode
            },
            success: res => {
                console.log(res,'获取最低时长1111111111')
              if(res.code == 1){
                  this.setData({

                    order_min_time:res.data.order_min_time
                  })
                // wx.showToast({
                //     title:"",
                //     icon: 'none'
                //   })
              }else{
                wx.showToast({
                  title:'获取失败',
                  icon: 'none'
                })
              }
            }
          }, 1);
    },
    // 
    delalhadel(){
      app.ajax({
        url: '/api/order/roomDetail',
        data:{
          room_id:this.data.rooms_ids},
        success: res => {
            if(res.code == 1){
                this.setData({
       
                    
                })
            }else{
            }
        }
    }, 1);

    },
    reserves(e){
        let imageUrl = e.currentTarget.dataset.img;
        console.log(imageUrl, 'imageUrl');
        wx.previewImage({
            urls: imageUrl, // 需要预览的图片链接列表
            current: imageUrl[0] // 当前显示的图片链接
        });

    },
    confirm_times(){
      
          let  data=this.data.times
        let kong=data.map(function(item,index){
          item.index=index+1
           return  item
           }) 
           data=kong
         console.log(kong,'---')
            
    // 最下方
            // 更新时间
            this.saveChosedTimes()
           
            //   this.confirmtimehaderl()
             
          let TotalPrices=Number(this.data.room.price) * this.data.nums+Number(this.data.deposit)-Number(wx.getStorageSync('couponmoney')||0)
            this.setData({
                // selectTime: false,
                TotalPrice:TotalPrices.toFixed(2),
                // -Number(this.data.user.money)
                // zd_t: this.data.zd_t=this.data.nums,
                // sf_price:Number(this.data.room.price) * this.data.nums+this.data.deposit,
            });
            console.log(this.data.TotalPrice,'this.data.TotalPricethis.data.TotalPrice')
          this.alldateshadel()
    },
    // alldetails(){
    
    //     app.ajax({
    //         url: '/api/index/storeDetail',
    //         data: {
    //           id: this.data.id,
    //           page: this.data.page,
    //         },
        
    //     })

    // }


})